package com.jingzhongbao.concurrent.lock;

import java.util.Random;
/**
 * User:jzb
 * Date:2018/11/15
 * Time:12:53
 * 消费者
 */
public class Consumer implements Runnable {
	/**
     * 篮子
     */
	private Bucket bucket;

	public Consumer(Bucket bucket) {
		super();
		this.bucket = bucket;
	}

	@Override
	public void run() {
		while (true) {
			// 获取锁
			bucket.getLock().lock();
			String obj = bucket.fetch();
			if (null == obj) {
				System.out.println(Thread.currentThread().getName() + ":篮子空了");
				// 通知生产者生产
				bucket.getAddLock().signalAll();
				try {
					// 消费者等待
					bucket.getFetchLock().await();
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					bucket.getLock().unlock();
				}
			} else {
				// 进行消费
				System.out.println(Thread.currentThread().getName() + ":消费了"
						+ obj);
				bucket.getLock().unlock();
				// 消费完后，随机休息[1,5]秒钟
				try {
					Thread.sleep(new Random().nextInt(5) * 1000 + 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
